<template>
  <div>
    <el-form inline>
      <el-form-item label="日期:">
        <c-radio-group
          v-model="dataType"
          number-key
          is-button
          size="small"
          :options="enumDataType"
          @change="handleDateTypeChange"
        ></c-radio-group>
      </el-form-item>
      <el-form-item label="时段查询:" class="ml-3">
        <el-date-picker
          style="width: 150px"
          v-model="timeStart"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="查询开始时间"
        ></el-date-picker>
        <span class="px-1">至</span>
        <el-date-picker
          style="width: 150px"
          v-model="timeEnd"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="查询结束时间"
        ></el-date-picker>
        <el-button icon="el-icon-search" class="ml-1" :loading="loading" @click="handleDateChange">
          查询
        </el-button>
      </el-form-item>
    </el-form>

    <div>
      <el-echarts
        ref="chart"
        height="300"
        theme="green"
        :loading="loading"
        :option="option"
      ></el-echarts>
    </div>
  </div>
</template>

<script>
// import { echartsXFormatter } from '@vimi/utils-tool'
import { getRfidCount } from '@/credit/views/city/self/after/rfid/index'

export default {
  components: {},
  props: {
    deviceId: String,
    devices: Array,
    farmId: String,
  },
  data() {
    return {
      loading: false,
      dataType: 0,
      enumDataType: [
        { label: '近7天', value: 0, day: 7 },
        { label: '近30天', value: 1, day: 30 },
        { label: '近3个月', value: 2, day: 90 },
        { label: '近12个月', value: 3, day: 360 },
      ],
      timeStart: '',
      timeEnd: '',

      option: {},
    }
  },
  computed: {
    watchId() {
      return this.farmId + this.deviceId
    },
  },
  watch: {
    watchId: {
      handler: function () {
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    getData() {
      if (!this.deviceId && !this.farmId) return
      this.handleDateTypeChange()
    },

    getRfidData(start, end) {
      if (!this.deviceId && !this.farmId) {
        return
      }
      this.loading = true
      getRfidCount({
        deviceId: this.deviceId || '',
        startTime: start,
        endTime: end,
        farmId: this.farmId,
      })
        .then(res => {
          const xData = []
          const aData = []

          for (const data of res) {
            xData.push(this.$utils.dateFormat(new Date(data.start_time), 'yyyy-MM-dd hh:mm'))
            aData.push(data.count)
          }

          this.parseOption({ xData, aData })
        })
        .finally(() => {
          this.loading = false
        })
    },

    getDateFromDay(day = 7) {
      const endDate = new Date()
      const startDate = new Date(endDate - day * 8.64e7)
      return [
        this.$utils.dateFormat(startDate, 'yyyy-MM-dd'),
        this.$utils.dateFormat(endDate, 'yyyy-MM-dd'),
      ]
    },

    // 自定义时段查询
    handleDateTypeChange() {
      const { day } = this.enumDataType[this.dataType]
      if (!day) return
      this.timeStart = ''
      this.timeEnd = ''
      const [start, end] = this.getDateFromDay(day)
      this.getRfidData(start, end)
    },

    // 时段查询
    handleDateChange() {
      if (!this.timeStart) {
        return this.$message.error('请选择开始时间')
      }
      if (!this.timeEnd) {
        return this.$message.error('请选择结束时间')
      }
      this.dataType = -1
      this.getRfidData(this.timeStart, this.timeEnd)
    },

    // 设置图表
    parseOption({ xData, aData }) {
      const showCount = 30 // 默认显示数据条数
      const { length } = xData
      const hasZoom = length > showCount
      const zoomStart = length === 0 || !hasZoom ? 0 : (100 * (length - showCount)) / length

      this.option = {
        title: {
          text: '',
        },
        tooltip: {
          trigger: 'axis',
          formatter: `{b}<br>{a}: {c}`,
        },
        legend: {
          data: ['时间'],
          show: false,
        },
        toolbox: {
          show: true,
          right: 40,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ['line', 'bar'] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        grid: {
          top: 40,
          left: 70,
          right: 50,
          bottom: 80,
        },
        xAxis: {
          type: 'category',
          data: xData,
          axisLabel: {
            align: 'left',
            formatter: v => {
              const arr = v.split(' ')
              return `${arr?.[1] ?? ''} \n${arr?.[0] ?? ''}`
            },
          },
          splitLine: {
            show: true,
            interval: ~~(length / showCount),
          },
        },
        yAxis: {
          type: 'value',
          name: '数量',
          splitArea: {
            show: false,
          },
          splitLine: {
            show: true,
          },
        },
        series: [
          {
            name: '数量',
            type: 'bar',
            barMaxWidth: 40,
            data: aData,
            smooth: true,
            label: {
              show: true,
              position: 'top',
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: '#CAECD0' },
                  { offset: 1, color: '#ffffff' },
                ],
              },
            },
          },
        ],
        dataZoom: [
          {
            show: true,
            fillerColor: 'rgba(66, 189, 86, 0.1)',
            realtime: true,
            xAxisIndex: 0,
            zoomOnMouseWheel: false,
            moveOnMouseWheel: false,
            start: zoomStart,
            end: 100,
          },
        ],
      }
    },
    resize() {
      this.$nextTick(() => {
        const { chart } = this.$refs
        chart && chart.resize()
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
